package com.hcinfos.gsoo.view;

import com.hcinfos.gsoo.util.AsyncImageLoader;
import com.hcinfos.gsoo.util.AsyncImageLoader.ImageCallback;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;

/**
 * 自定义可以自动从网络加载图片的组件
 * 
 * @author john
 * 
 */
public class UrlImageView extends ImageView {
	AsyncImageLoader asyncImageLoader;

	public UrlImageView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		init();
	}

	public UrlImageView(Context context, AttributeSet attrs) {
		super(context, attrs);
		init();
	}

	public UrlImageView(Context context) {
		super(context);
		init();
	}

	private void init() {
		asyncImageLoader = new AsyncImageLoader();

	}

	public void setImageUrl(String url, int defaultDrawable, int errorDrawable,
			final int type) {

		// 0 是背景 1 是图片
		if (type == 0) {
			this.setBackgroundResource(defaultDrawable);
		} else {
			this.setImageResource(defaultDrawable);
		}

		this.setTag(url);
		Drawable cachedImage = asyncImageLoader.loadDrawable(url,
				new ImageCallback() {
					public void imageLoaded(Drawable imageDrawable,
							String imageUrl) {
						if (type == 0) {
							setBackgroundDrawable(imageDrawable);
						} else {
							setImageDrawable(imageDrawable);
						}

					}
				});
		if (cachedImage == null) {
			if (type == 0) {
				setBackgroundResource(errorDrawable);
			} else {
				setImageResource(errorDrawable);
			}

		} else {
			if (type == 0) {
				setBackgroundDrawable(cachedImage);
			} else {
				setImageDrawable(cachedImage);
			}

		}
	}
}
